package com.saicmotor.hk2.service.Impl;

import com.saicmotor.hk2.mapper.CommonMapper;
import com.saicmotor.hk2.mapper.UserRoleMapper;
import com.saicmotor.hk2.model.UserRole;
import com.saicmotor.hk2.model.UserRoleInfo;
import com.saicmotor.hk2.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    CommonMapper commonMapper;


    @Override
    public void insertUserRoleInfo(String userName, String roleName) {
        userRoleMapper.insertUserRoleInfo(commonMapper.getIdByName("user", userName),
                commonMapper.getIdByName("role", roleName));
    }

    @Override
    public List<UserRole> getAll() {
        return userRoleMapper.getAll();
    }

    @Override
    public List<UserRoleInfo> getAllInfo() {
        return userRoleMapper.getAllInfo();
    }

    @Override
    public void deleteByUserName(String userName) {
        userRoleMapper.deleteByUserId(commonMapper.getIdByName("user",userName));
    }

    @Override
    public void deleteByRoleName(String roleName) {
        userRoleMapper.deleteByRoleId(commonMapper.getIdByName("role",roleName));
    }

    @Override
    public void updateUser(String oldUserName,String newUserName,String roleName) {
        userRoleMapper.updateUser(commonMapper.getIdByName("user",oldUserName),
                commonMapper.getIdByName("user",newUserName),
                commonMapper.getIdByName("role",roleName));
    }

    @Override
    public void updateRole(String oldRoleName,String newRoleName,String userName) {
        userRoleMapper.updateRole(commonMapper.getIdByName("role",oldRoleName),
                commonMapper.getIdByName("role",newRoleName),
                commonMapper.getIdByName("user",userName));
    }

    @Override
    public boolean checkRecord(String userName, String roleName) {
        if (commonMapper.getIdByName("user", userName) == null ||
                commonMapper.getIdByName("role", roleName) == null) {
            return false;
        } else if (!userRoleMapper.getIdByUserRole(commonMapper.getIdByName("user", userName),
                commonMapper.getIdByName("role", roleName)).isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void createUserRoleTable(String tableName) {
        userRoleMapper.createUserRoleTable(tableName);
    }
}
